/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.leo.base_project.activity.module_Impl.bluImpl;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.leo.base_project.R;
import com.leo.base_project.module.blu.BTUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Activity for scanning and displaying available Bluetooth LE devices.
 */
public class DeviceScanActivity extends Activity implements OnClickListener {

    // private LeDeviceListAdapter mLeDeviceListAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 15000;

    private DeviceListAdapter mDevListAdapter;
    ListView lv_bleList;

    private ProgressDialog progressDialog;

    // 广播接收发现蓝牙设备
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            progressDialog.dismiss();
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                Log.d("TAG", "开始扫描...");
            }
            // 如果发现设备则添加至列表
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    // 添加到ListView的Adapter
                    mDevListAdapter.addDevice(device);
                    mDevListAdapter.notifyDataSetChanged();
                }
            }

            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.d("TAG", "扫描结束.");
            }

            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device == null || TextUtils.isEmpty(device.getName())) {
                return;
            }
            mDevListAdapter.addDevice(device);
            mDevListAdapter.notifyDataSetChanged();
        }
    };

    Long user_id;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_scan);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在搜索蓝牙...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        mHandler = new Handler();

        user_id = getIntent().getLongExtra("user_id", 0);

        // 判断BLE是否能启用
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }

        // 创建蓝牙适配器
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        assert bluetoothManager != null;
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // 判断蓝牙是否能开启
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 如果本地蓝牙没有开启，则开启  
        if (!mBluetoothAdapter.isEnabled()) {
            // 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择，比如用户单击了Yes开启，
            // 那么将会收到RESULT_OK的结果，
            // 如果RESULT_CANCELED则代表用户不愿意开启蓝牙
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(mIntent, 1);
        }

        // 注册广播接收器。
        // 接收蓝牙发现
        IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filterFound);

        IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(mReceiver, filterStart);

        IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filterFinish);

        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mReceiver, intent);

        lv_bleList = findViewById(R.id.lv_bleList);

        mDevListAdapter = new DeviceListAdapter();
        lv_bleList.setAdapter(mDevListAdapter);

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                mDevListAdapter.addDevice(device);
            }
        }

        // 设置ListView点击适配器(跳转到设备页面)
        // 是否有更好的传递方式？比如 Eventbus
        lv_bleList.setOnItemClickListener((parent, view, position, id) -> {
            if (mDevListAdapter.getCount() > 0) {
                BluetoothDevice device1 = mDevListAdapter.getItem(position);
                if (device1 == null) return;
                Intent intent1 = new Intent(DeviceScanActivity.this, BluTestActivity.class);
                intent1.putExtra("user_id", user_id);
                intent1.putExtra(BTUtils.EXTRAS_DEVICE_NAME, device1.getName());
                intent1.putExtra(BTUtils.EXTRAS_DEVICE_ADDRESS, device1.getAddress());
                if (mScanning) {
                    mBluetoothAdapter.cancelDiscovery();
                    mScanning = false;
                }
                setResult(BTUtils.SUCCESS,intent1);
                finish();
            }
        });
    }

    public void onClick(View v) {
        v.getId();
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.main, menu);
//        if (!mScanning) {
//            menu.findItem(R.id.menu_stop).setVisible(false);
//            menu.findItem(R.id.menu_scan).setVisible(true);
//        } else {
//            menu.findItem(R.id.menu_stop).setVisible(true);
//            menu.findItem(R.id.menu_scan).setVisible(false);
//        }
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.menu_scan:
//                scanLeDevice(true);
//                mDevListAdapter.clear();
//                mDevListAdapter.notifyDataSetChanged();
//                break;
//            case R.id.menu_stop:
//                scanLeDevice(false);
//                break;
//        }
//        return true;
//    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(() -> {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                invalidateOptionsMenu();
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
            mBluetoothAdapter.startDiscovery();
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        invalidateOptionsMenu();
    }

    private LeScanCallback mLeScanCallback = new LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            runOnUiThread(() -> {
                if (device != null && device.getName() != null) {
                    mDevListAdapter.addDevice(device);
                    mDevListAdapter.notifyDataSetChanged();
                }
            });
        }
    };

    @Override
    protected void onResume() {//打开APP时扫描设备
        super.onResume();
        scanLeDevice(true);
    }

    @Override
    protected void onPause() {//停止扫描
        super.onPause();
        scanLeDevice(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    public void exit(View view) {
        finish();
    }

    class DeviceListAdapter extends BaseAdapter {

        private List<BluetoothDevice> mBleArray;
        private ViewHolder viewHolder;

        public DeviceListAdapter() {
            mBleArray = new ArrayList<>();
        }

        /*
         * Description 只有等于BTUtils.EXTRAS_DEVICE_NAME名称的设备才能被搜索
         * Date 2020/7/20 14:25
         **/
        public void addDevice(BluetoothDevice device) {
            if (device != null
                    && device.getName() != null
                    && !mBleArray.contains(device)) {
                mBleArray.add(device);
            }
        }

        public void clear() {
            mBleArray.clear();
        }

        @Override
        public int getCount() {
            return mBleArray.size();
        }

        @Override
        public BluetoothDevice getItem(int position) {
            return mBleArray.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(DeviceScanActivity.this).inflate(
                        R.layout.item_device, null);
                viewHolder = new ViewHolder();
                viewHolder.tv_devName = convertView
                        .findViewById(R.id.device_name);
                viewHolder.tv_devAddress = convertView
                        .findViewById(R.id.device_address);
                convertView.setTag(viewHolder);
            } else {
                convertView.getTag();
            }

            // add-Parameters
            BluetoothDevice device = mBleArray.get(position);
            String devName = device.getName();
            if (devName != null && devName.length() > 0) {
                viewHolder.tv_devName.setText(devName);
            } else {
                viewHolder.tv_devName.setText("未知设备");
            }
            viewHolder.tv_devAddress.setText(device.getAddress());

            return convertView;
        }

    }

    static class ViewHolder {
        TextView tv_devName, tv_devAddress;
    }


}